#define _DEFAULT_SOURCE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#include "utils.h"
#include "timestamp.h"


int64_t get_uptime(void)
{
    char buf[128];
    load("/proc/uptime", buf, sizeof(buf) - 1);

    char *ctx = buf;
    char *token;
    int i = 0;
    while ((token = strsep(&ctx, " \n")) != NULL) {
        if (!*token)
            continue;

        // take second column
        if (i++ == 0)
            break;
        //printf("> %s\n", token);
    }

    return (int64_t)atoll(token);
}

int64_t get_utcsec(void)
{
    return (int64_t)time(NULL);
}

int64_t get_timefmt(int64_t time, char buf[26])
{
    if (time < 0) {
        return -1;
    }
    // change to localtime
    struct tm *tm_info = localtime(&time);
    if (tm_info == NULL) {
        perror("localtime");
        return -2;
    }

    // format timestamp
    strftime(buf, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    return time;
}



#define HELP    \
    "timestamp [option]\n" \
    "\n" \
    "options:\n" \
    "                   show current time\n" \
    "   -u              show uptime\n" \
    "   -h, --help      show help message\n"

int main(int argc, char *argv[])
{
    char fmt0[26];
    char fmt1[26];

    int has_uptime = 0;

    if (argc == 1) {
        has_uptime = 0;
    } else if (argc == 2) {
        if (strcmp(argv[1], "-u") == 0) {
            has_uptime = 1;
        }

        if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
            goto help;
        }
    } else {
        goto help;
    }

    int64_t now, up_abs, up_rel;
    now = get_timefmt(get_utcsec(), fmt0);

    if (has_uptime) {
        up_abs= get_uptime();
        up_rel = get_timefmt(now - up_abs, fmt1);
        printf("UPTIME %ld %ld %s\n", up_abs, up_rel, fmt1);
    }

    printf("TIME %ld %s\n", now, fmt0);

    return 0;

help:
    printf(HELP);
    return -1;
}
